#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 字符串匹配和搜索
问题: 你想匹配或者搜索特定模式的文本
提示 :
    1. 仅仅是做一次简单的文本匹配/搜索操作的话，可以略过编译部分，直接使用 re 模块级别的函数
    2. 做大量的匹配和搜索操作的话，最好先编译正则表达式，然后再重复使用它
"""
import re

msg = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
print(f"{msg = }")
pattern = r'\d+/\d+/\d+'
print(f"{pattern = }")


def recipe1():
    """调用基本字符串方法"""
    text = 'yeah, but no, but yeah, but no, but yeah'
    print(f"{text = }")
    # Exact match
    print(f"{text == 'yeah' = }")
    # Match at start or end
    print(f"{text.startswith('yeah') = }")
    print(f"{text.endswith('no') = }")
    # Search for the location of the first occurrence
    print(f"{text.find('no') = }")


def recipe2():
    """复杂的匹配需要使用正则表达式和 re 模块"""
    text1 = '11/27/2012'
    text2 = 'Nov 27, 2012'
    print(f"{text1 = }")
    print(f"{text2 = }")

    # 简单匹配
    print(f"{re.match(pattern, text1) = }")
    print(f"{re.match(pattern, text2) = }")

    # 一个模式去做多次匹配，应该先将模式字符串预编译为模式对象
    datepat = re.compile(pattern)
    print(f"{datepat.match(text1) = }")

    print(f"{datepat.match(text2) = }")

    # 使用 findall()
    print(f"{datepat.findall(msg) = }")


def recipe3():
    """利用括号去捕获分组"""
    datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
    m = datepat.match('11/27/2012')
    print(f"{m = }")

    # Extract the contents of each group
    print(f"{m.group(0) = }")
    print(f"{m.group(1) = }")
    print(f"{m.group(2) = }")
    print(f"{m.group(3) = }")
    print(f"{m.groups() = }")

    month, day, year = m.groups()
    print(f"{'{} {} {}'.format(year, month, day) = }")

    dates = datepat.findall(msg)
    print(f"{dates = }")

    for month, day, year in dates:
        print(f"{'{}-{}-{}'.format(year, month, day) = }")

    # 以迭代方式返回匹配
    for m in datepat.finditer(msg):
        print(f"{m.groups() = }")

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()

if __name__ == '__main__':
    main()
